import express from 'express';
import { IncomingForm } from 'formidable';
import path from 'path';
import { zip } from '../../utils/index.js';

const router = express.Router();
const tinypng = router.post('/tools/tinypng', async (req, res, next) => {
    // 解析参数
    const form = new IncomingForm();
    form.parse(req).then(async (files) => {
        console.log(req.body)
        const file = files[1].file[0]
        const qt = files[0].qt[0] || 80;
        const { originalFilename } = file;
        const ext = path.extname(originalFilename);
        if (ext !== '.png') {
            res.statusCode = 400;
            res.end('Only support PNG file');
            return;
        }

        const result = await zip(file, qt);
        res.setHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        // 图片转base64
        const base64 = Buffer.from(result).toString('base64');
        const buffer = Buffer.from(base64, 'base64');
        res.end(JSON.stringify({
            code: 200,
            msg: '成功',
            data: {
                pic: base64,
                originSize: file.size,
                compressSize: buffer.byteLength
            }
        }));
    }).catch(error => {

    });
})

export {
    tinypng
}